﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;
using LiveCharts;
using LiveCharts.Wpf;

namespace HIWSystem.ViewModel
{
    public class AssemblyInfoEntryViewModel : ViewModelBase
    {
        #region 属性
        private string sn;
        /// <summary>
        /// 序列号
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private bool isFocusSn;
        /// <summary>
        /// 是否聚焦序列号文本框
        /// </summary>
        public bool IsFocusSn
        {
            get { return isFocusSn; }
            set { isFocusSn = value; this.RaisePropertyChanged(() => IsFocusSn); }
        }
        private ObservableCollection<TrackingCombineSnEntity> logs;
        /// <summary>
        /// 测试记录
        /// </summary>
        public ObservableCollection<TrackingCombineSnEntity> Logs
        {
            get { return logs; }
            set { logs = value; this.RaisePropertyChanged(() => Logs); }
        }
        private string countdown="00:02:00";

        public string Countdown
        {
            get { return countdown; }
            set { countdown= value; this.RaisePropertyChanged(() => Countdown); }
        }
        private SeriesCollection pieSeriesCollection;
        /// <summary>
        /// 饼状图系列集合
        /// </summary>
        public SeriesCollection PieSeriesCollection
        {
            get { return pieSeriesCollection; }
            set { pieSeriesCollection = value; this.RaisePropertyChanged(() => PieSeriesCollection); }
        }
        private SeriesCollection seriesCollection;
        /// <summary>
        /// 柱状图系列集合
        /// </summary>
        public SeriesCollection SeriesCollection
        {
            get { return seriesCollection; }
            set { seriesCollection = value; this.RaisePropertyChanged(() => SeriesCollection); }
        }
        private string[] labels;
        /// <summary>
        /// 标签《XAxis的标签信息》
        /// </summary>
        public string[] Labels
        {
            get { return labels; }
            set { labels = value; this.RaisePropertyChanged(() => Labels); }
        }
        private Func<double, string> formatter;
        /// <summary>
        /// YAxis格式化信息
        /// </summary>
        public Func<double, string> Formatter
        {
            get { return formatter; }
            set { formatter = value; this.RaisePropertyChanged(() => Formatter); }
        }
        private ObservableCollection<StationOutputEntity> outputs;
        /// <summary>
        /// 站位产量输出记录
        /// </summary>
        public ObservableCollection<StationOutputEntity> Outputs
        {
            get { return outputs; }
            set { outputs = value; this.RaisePropertyChanged(() => Outputs); }
        }

        #endregion

        #region 命令
        private RelayCommand loadedPageCmd;
        /// <summary>
        /// 页面加载命令
        /// </summary>
        public RelayCommand LoadedPageCmd
        {
            get 
            {
                if (loadedPageCmd==null)
                {
                    loadedPageCmd = new RelayCommand(LoadedPage);
                }
                return loadedPageCmd;
            }
            set { loadedPageCmd = value; }
        }

        private RelayCommand snKeyEnterCommand;
        /// <summary>
        /// 序列号回车事件命令
        /// </summary>
        public RelayCommand SNKeyEnterCommand
        {
            get 
            {
                if (snKeyEnterCommand==null)
                {
                    snKeyEnterCommand = new RelayCommand(SNKeyEntryHandle);
                }
                return snKeyEnterCommand; 
            }
            set { snKeyEnterCommand = value; }
        }
        

        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            ShowTodayStationOutputAsync();
        }

        /// <summary>
        /// 序列号回车处理
        /// </summary>
        private void SNKeyEntryHandle()
        {
            string pn = string.Empty;//机种信息
            string startTime = string.Empty;//开始时间
            string inputSn = string.Empty; //输入的序列号信息
            string retMsg = string.Empty;//数据库返回的状态码和状态信息
            string[] arrayMsg = new string[2]; //截取返回的状态码和状态信息
            DataTable dtTracking = new DataTable();
            TrackingEntity trackingEntity = new TrackingEntity();
            startTime = DateTime.Now.ToString();
            inputSn = this.SN.Trim().ToUpper() ?? "";
            if (!CheckSnInfo(inputSn))
                return;
            trackingEntity.Sn = inputSn;
            trackingEntity.Station = "ASSEMBLY";
            trackingEntity.Result = "PASS";
            trackingEntity.EquipmentName = Environment.MachineName;
            trackingEntity.StartTime = startTime;
            trackingEntity.StopTime = DateTime.Now.ToString();
            trackingEntity.Actor = LogInInfo.User;
            //retMsg = "OK|插入成功!"; --用于调试使用
            retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtTracking);
            arrayMsg = retMsg.Split('|');
            if (arrayMsg[0] == "OK")
            {
                //首次添加要初始化Log集合
                if (Logs == null)
                    Logs = new ObservableCollection<TrackingCombineSnEntity>();
                Logs.Add(new TrackingCombineSnEntity
                {
                    Sn = inputSn,
                    PN=BusinessProcess.GetPNBySn(inputSn),
                    Station="ASSEMBLY",
                    EquipmentName = Environment.MachineName,
                    Result = trackingEntity.Result,
                    Actor = LogInInfo.User,
                    CreateAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
                //根据时间进行降序排序，便于将最近一条记录显示再最上面。
                var a= Logs.OrderByDescending(x =>Convert.ToDateTime(x.CreateAt)).ToList();
                Logs = new ObservableCollection<TrackingCombineSnEntity>();
                for (int i = 0; i < a.Count; i++)
                {
                    Logs.Add(new TrackingCombineSnEntity
                    {
                        Sn = a[i].Sn ?? "",
                        PN=a[i].PN??"",
                        Station = a[i].Station ?? "",
                        EquipmentName =a[i].EquipmentName??"",
                        Result =a[i].Result??"",
                        Actor =a[i].Actor??"",
                        CreateAt =a[i].CreateAt??"",
                    }) ;
                }
                this.SN = "";
                this.IsFocusSn = true;
            }
            else
            {
                MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 检查录入的序列号信息
        /// </summary>
        /// <returns></returns>
        private bool CheckSnInfo(string sn)
        {
            if (string.IsNullOrEmpty(sn))
            {
                MessageBox.Show("序列号信息不能为空,请输入序列号信息.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }
            if (!BusinessProcess.SNIsExists(sn))
            {
                MessageBox.Show("序列号【" + this.SN + "】在系统中不存在,请重新输入.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }
        /// <summary>
        /// 显示今天工位的产出《异步》
        /// </summary>
        private async void ShowTodayStationOutputAsync()
        {
            DateTime totalTime = DateTime.Parse(this.Countdown); //总的计时
            string strCurrentTime = string.Empty;//当前时间
            await Task.Run(()=> 
            {
                while (true)
                {
                    totalTime = totalTime.AddSeconds(-1);
                    strCurrentTime =totalTime.Hour.ToString("00")+":"+totalTime.Minute.ToString("00") + ":" + totalTime.Second.ToString("00");
                    Application.Current.Dispatcher.BeginInvoke((Action)(()=>{ this.Countdown = strCurrentTime; }));
                    if (strCurrentTime=="00:00:00")//倒计时结束
                    {
                        //PASS数据
                        List<double> passData = new List<double>();
                        //FAIL数据
                        List<double> failData = new List<double>();
                        //X轴标签
                        List<string> xAixsLables = new List<string>();
                        string retMsg = string.Empty;//接收返回的信息 Y|插入成功 或者 N|插入失败..
                        string[] arrayMsg = new string[2];
                        string startTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:01";
                        //string startTime = "2022-01-01 00:00:01"; //调试使用
                        string stopTime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
                        DataTable dtOutput = new DataTable();
                        retMsg = BusinessProcess.StatisticsStationOutput(out dtOutput, "", "Assembly", startTime, stopTime,"1"); //最后参数1表示查询最后一次记录
                        arrayMsg = retMsg.Split('|');
                        if (arrayMsg[0] == "Y")
                        {
                            if (dtOutput.Rows.Count > 0)
                            {
                                //for (int i = 0; i < dtOutput.Rows.Count; i++)
                                //{
                                //    xAixsLables.Add(dtOutput.Rows[i]["PN"].ToString());
                                    
                                //    passData.Add( Convert.ToDouble(dtOutput.Rows[i]["Pass"] == DBNull.Value ? "0" : dtOutput.Rows[i]["Pass"].ToString() ?? "0"));
                                //    failData.Add( Convert.ToDouble(dtOutput.Rows[i]["Fail"] == DBNull.Value ? "0" : dtOutput.Rows[i]["Fail"].ToString() ?? "0"));
                                //}
                                Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                                {
                                 
                                    ////添加PASS的数据   
                                    //ChartValues<double> passValues = new ChartValues<double>();
                                    //for (int i = 0; i < passData.Count; i++)
                                    //{
                                    //    passValues.Add(passData[i]);
                                    //}
                                    //ColumnSeries seriesPowerSave = new ColumnSeries();
                                    //seriesPowerSave.Title = "PASS";
                                    //seriesPowerSave.Fill = new SolidColorBrush(Color.FromRgb(34, 139, 34));
                                    //seriesPowerSave.DataLabels = true;//是否显示柱子上的数值
                                    //seriesPowerSave.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
                                    ////显示文本内容
                                    //seriesPowerSave.LabelPoint = p => p.Y.ToString();// 显示柱子上的格式
                                    //seriesPowerSave.Values = passValues;
                                    ////柱子宽度
                                    //seriesPowerSave.Width = 20;
                                    //seriesPowerSave.MaxColumnWidth = 20;//正常柱子宽度
                                    //SeriesCollection = new SeriesCollection();
                                    //SeriesCollection.Add(seriesPowerSave);

                                    ////添加FAIL的数据
                                    //ChartValues<double> failValues = new ChartValues<double>();
                                    //for (int i = 0; i < failData.Count; i++)
                                    //{
                                    //    failValues.Add(failData[i]);
                                    //}
                                    //seriesPowerSave = new ColumnSeries();
                                    //seriesPowerSave.Title = "FAIL";
                                    //seriesPowerSave.Fill = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                                    //seriesPowerSave.DataLabels = true;//是否显示柱子上的数值
                                    //seriesPowerSave.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
                                    ////显示文本内容
                                    //seriesPowerSave.LabelPoint = p => p.Y.ToString();// 显示柱子上的格式
                                    //seriesPowerSave.Values = failValues;
                                    ////柱子宽度
                                    //seriesPowerSave.Width = 20;
                                    //seriesPowerSave.MaxColumnWidth = 20;//正常柱子宽度
                                    //SeriesCollection.Add(seriesPowerSave);
                                    //this.Labels = xAixsLables.ToArray();
                                    //Formatter = value => value.ToString("N");

                                    //添加数据到汇总表
                                    Outputs = new ObservableCollection<StationOutputEntity>();
                                    for (int i = 0; i < dtOutput.Rows.Count; i++)
                                    {
                                        Outputs.Add(new StationOutputEntity 
                                        { 
                                          PN=dtOutput.Rows[i]["PN"].ToString()??"",
                                          Station=dtOutput.Rows[i]["Station"].ToString()??"",
                                          Pass=dtOutput.Rows[i]["Pass"].ToString()??"",
                                          Fail=dtOutput.Rows[i]["Fail"].ToString()??"",
                                          Total=dtOutput.Rows[i]["Total"].ToString()??""
                                        });
                                    }
                                }));
                            }
                        }
                        Application.Current.Dispatcher.BeginInvoke((Action)(() => { this.Countdown ="00:02:00"; }));
                        totalTime = DateTime.Parse("00:02:00");
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(1)); //间隔一秒
                }
            });

        }
        #endregion
    }
}
